package com.jd.dl.web;

import java.util.ArrayList;
import java.util.List;

import com.jd.dl.dao.constant.QueryConstants;
import com.jd.dl.dao.util.HqlCriterions;
import com.jd.dl.pojo.Task;
import com.jd.dl.pojo.User;
import com.jd.dl.service.DictionaryService;
import com.jd.dl.service.TaskService;
import com.jd.dl.service.UserService;
import com.jd.dl.service.exception.ErrorMessage;
import com.jd.dl.service.exception.ServiceException;
import com.jd.dl.util.DES;
import com.jd.dl.util.EncryptUtil;
import com.jd.dl.util.Pager;


public class UserAction extends BaseAction {

	private static final long serialVersionUID = -4018571604337249963L;
	private static final long TASK_ARRIVED_ID = 102;
	private static final long TASK_ASSIGNED_ID = 101;
	private Long id;

	private UserService userService;
	private TaskService taskService;
	private DictionaryService dictionaryService;
	private String phoneNumber;
	private String password;
	private Double lon;
	private Double lat;

	public Double getLon() {
		return lon;
	}

	public void setLon(Double lon) {
		this.lon = lon;
	}

	public Double getLat() {
		return lat;
	}

	public void setLat(Double lat) {
		this.lat = lat;
	}

	private User user = new User();
	private Long[] permission;
	private List<Task> tasks = new ArrayList<Task>();
	private Long taskId;
	private Task task;
	private Result result = new Result();
	

	public String login(){
		try {
			
			User user = userService.login(phoneNumber, password);
			result.setSuccess(user != null);
		} catch (ServiceException e) {
			e.printStackTrace();
			result.setSuccess(false);
		}
		return SUCCESS;
	}
	
	public String logout(){
		result.setSuccess(true);
		return SUCCESS;
	}
	
	public String arrived(){
		try {
			Task task = taskService.get(taskId);
			task.setTaskStatus(dictionaryService.load(TASK_ARRIVED_ID));
			task.setArrivedLat(lat);
			task.setArrivedLon(lon);
			taskService.update(task);
			result.setSuccess(true);
			return SUCCESS;
		} catch (ServiceException e) {
			result.setSuccess(false);
			e.printStackTrace();
			return SUCCESS;
		}
	}
	
	public String register(){
		try {
			User newU = new User();
			newU.setPhoneNumber(phoneNumber);
			newU.setPassword(EncryptUtil.getStringMD5(password));
			userService.add(newU);
			result.setSuccess(true);
		} catch (ServiceException e) {
			e.printStackTrace();
			result.setSuccess(false);
		}
		return SUCCESS;
	}
	
	public String getTaskList(){
		HqlCriterions hc = new HqlCriterions();
		hc.and(QueryConstants.Task.USER+"."+QueryConstants.User.PHONE_NUMBER, phoneNumber,
				QueryConstants.EQ);

		hc.and(QueryConstants.Task.TASK_STATUS+"."+QueryConstants.Dictionary.DICTIONARY_ID, TASK_ASSIGNED_ID,
				QueryConstants.EQ);
		tasks = taskService.getList(hc.getHqlString());
		return SUCCESS;
	}
	
	public String getTaskById(){
		task = taskService.get(taskId);
		return SUCCESS;
	}
	
	@Override
	public String execute() throws Exception {

		return SUCCESS;
	}


	public Result getResult() {
		return result;
	}

	public void setResult(Result result) {
		this.result = result;
	}

	public String userInfo() {
		if (id != null) {
			user = userService.get(id);
		}
		return SUCCESS;
	}

	public String updateUser() throws ServiceException {
		try {
			if (user.getUserId() == null) {
				userService.add(user);
			} else {
				userService.update(user);
			}
		} catch (ServiceException e) {
			addActionError(e.getErrorMessage());
			return INPUT;
		}
		return SUCCESS;
	}



	public Long getId() {
		return id;
	}

	public void setId(Long id) {
		this.id = id;
	}

	public Pager getPager() {
		return pager;
	}

	public void setUserService(UserService userService) {
		this.userService = userService;
	}

	public TaskService getTaskService() {
		return taskService;
	}



	public void setTaskService(TaskService taskService) {
		this.taskService = taskService;
	}



	public UserService getUserService() {
		return userService;
	}



	public User getUser() {
		return user;
	}

	public void setUser(User user) {
		this.user = user;
	}

	public String changepwd() {
		User nuser = (User) userService.load(super.getUser().getUserId());
		nuser.setPassword(DES.encrypt(user.getPassword()));
		try {
			userService.update(nuser);
		} catch (ServiceException e) {
			log.error("change user password error.", e);
			addActionError(e.getErrorMessage());
			return ERROR;
		} catch (Exception e) {
			log.error("change user password error.", e);
			addActionError(ErrorMessage.UNKNOW_ERROR);
			return ERROR;
		}
		addActionMessage("密码已修改");
		return SUCCESS;
	}

	public String userMenu(){
		return SUCCESS;
	}
//	public String permissionInfo() {
//		user = userService.load(id);
//		functions = functionService.getTree();
//		// functions=new ArrayList<Function>();
//		// Function f=new Function();
//		// f.setFunctionName("asdf");
//		// f.setFunctionId(new Long(1));
//		//				
//		// Set<Function> children = new HashSet<Function>();
//		// Function f1=new Function("ffff");
//		// f1.setFunctionId(new Long(0));
//		// children.add(f1);
//		// f.setChildren(children);
//		// functions.add(f);
//		//				
//		// Set<Permission> permissions = new HashSet<Permission>();
//		// Permission o=new Permission();
//		// o.setFunction(f1);
//		// permissions.add(o);
//		// user.setPermissions(permissions);
//		return SUCCESS;
//	}

//	public String userMenu() {
//		List<Function> funs = functionService.getTree();
//		functions = new ArrayList<Function>();
//		for (Function fun : funs) {
//			functions.add(fun);
//		}
//		if(super. getUser().getRole().isAdmin()){
//			return SUCCESS;
//		}
//		List<Permission> pers =super. getUser().getRole().getPermissions();
//		Collections.sort(pers);
//		for (Function function : functions) {
//			List<Function> child = new ArrayList<Function>();
//			for (Iterator<Permission> iterator = pers.iterator(); iterator.hasNext();) {
//				Function pf = iterator.next().getFunction();
//				if (pf.getParent().getFunctionId().longValue() == function.getFunctionId()
//						.longValue())
//					child.add(pf);
//			}
//			Collections.sort(child);
//			function.setChildren(child);
//		}
//		// functions=functionService.getTree();
//		return SUCCESS;
//	}

	public String showMain() {
//		if(super.getUser().getRole().isAdmin()){
//			return SUCCESS;
//		}
//		List<Permission> pers = getUser().getRole().getPermissions();
//		for (Permission permission : pers) {
//			if (permission.getFunction().getIsDefault()) {
//				this.session.put(SessionKey.DEFAULT_FUNCTION, permission.getFunction());
//				return SUCCESS;
//			}
//		}
//		this.session.put(SessionKey.DEFAULT_FUNCTION, pers.get(0).getFunction());
		return SUCCESS;

	}


	public Long[] getPermission() {
		return permission;
	}

	public void setPermission(Long[] permission) {
		this.permission = permission;
	}


	public int getPage() {
		return page;
	}

	public void setPage(int page) {

		this.page = page;

	}

	public String getPhoneNumber() {
		return phoneNumber;
	}

	public void setPhoneNumber(String phoneNumber) {
		this.phoneNumber = phoneNumber;
	}

	public String getPassword() {
		return password;
	}

	public void setPassword(String password) {
		this.password = password;
	}

	public List<Task> getTasks() {
		return tasks;
	}

	public void setTasks(List<Task> tasks) {
		this.tasks = tasks;
	}

	public Long getTaskId() {
		return taskId;
	}

	public void setTaskId(Long taskId) {
		this.taskId = taskId;
	}

	public Task getTask() {
		return task;
	}

	public void setTask(Task task) {
		this.task = task;
	}
	
	public DictionaryService getDictionaryService() {
		return dictionaryService;
	}

	public void setDictionaryService(DictionaryService dictionaryService) {
		this.dictionaryService = dictionaryService;
	}

	public class Result {
		private Boolean success = false;
		
		public Boolean getSuccess() {
			return success;
		}
		public void setSuccess(Boolean success) {
			this.success = success;
		}
		
		
		
	}

}
